from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from need.models import SoftwareNeed, NeedHandle
from software.models import Software, SoftwareVersion
from log.models import UserLog
from announcement.views.views_anno import createAnnouncement, announcementCreate
import pdb, os
import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def addNeed(request, *args, **kwargs):
    """
        url    : /need/raise/
        method : POST

    :param request:
            token:data.token,//token
            sofawareId:data.sofawareId,//软件id
            title:data.title,
            needContent:data.needContent,//需求内容

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType
    software = SoftwareVersion.objects.get(pk=requestParam['softwareVersionId'])

    if userType == '3':
        need = SoftwareNeed.objects.create(
            user=user,
            softwareVersion=software,
            title=requestParam['title'],
            needContent=requestParam['needContent'],
        )
        announcementCreate(
            type='need',
            num='1',
            userType='2',
            userId=user.id,
            softwareVersionId=software.id,
            IdNum=need.id
        )
        option = '提出了' + str(need.title) + '需求'
        userIP = datacheck.getIP(request)
        log = UserLog.objects.create(
            user=user,
            userIP=userIP,
            operate=option,
        )
    else:
        data = {
            'code': 0,
            'msg': 'userType error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def needOption(request, *args, **kwargs):
    """
        url    : /question/option/
        method : POST

    :param request:
            token: data.token, // 用户的秘钥
            needId:data.needId,//需求id
            option:data.option,//管理人员 0:自己处理、1表示交给开发人员，2：删除、3：恢复、4导出
                                //
            verify:data.verify,//0表示解决需求，1表示驳回需求
            result:data.result,//解决方案或驳回理由

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    need = SoftwareNeed.objects.get(pk=requestParam['needId'])

    if userType == '2':
        if requestParam['option'] == '0':
            if requestParam['verify'] == '0':
                handle = NeedHandle.objects.create(
                    user=user,
                    need=need,
                    handleContent=requestParam['result'],
                )
                need.needState = 1
                need.examineState = 1
                need.isExamine = True
                need.ishandle = True
                need.save()
                announcementCreate(
                    type='need',
                    num='2',
                    userId=user.id,
                    userType='3',
                    softwareVersionId=need.softwareVersion.id,
                    IdNum=need.id
                )
                option = '回复了' + str(need.title) + '需求'
                userIP = datacheck.getIP(request)
                log = UserLog.objects.create(
                    user=user,
                    userIP=userIP,
                    operate=option,
                )
            elif requestParam['verify'] == '1':
                reject = NeedHandle.objects.create(
                    user=user,
                    need=need,
                    rejectResult=requestParam['result'],
                )
                need.isExamine = True
                need.ishandle = True
                need.needState = 2
                need.examineState = 2
                need.save()
                announcementCreate(
                    type='need',
                    num='3',
                    userType='3',
                    userId=user.id,
                    softwareVersionId=need.softwareVersion.id,
                    IdNum=need.id
                )
                option = '驳回了' + str(need.title) + '需求'
                userIP = datacheck.getIP(request)
                log = UserLog.objects.create(
                    user=user,
                    userIP=userIP,
                    operate=option,
                )
            else:
                data = {
                    'code': 0,
                    'msg': 'verify error',
                }
                logger_request.info(data)
                return JsonResponse(data)

        elif requestParam['option'] == '1':
            need.examineState = 1
            need.isExamine = True
            need.save()
            logger_request.info('000000000000000000000')
            announcementCreate(
                type='need',
                num='1',
                userType='1',
                userId=need.user.id,
                softwareVersionId=need.softwareVersion.id,
                IdNum=need.id
            )
            logger_request.info('111111111111111111111')
            option = '将' + str(need.title) + '需求' + '交给开发人员处理'
            logger_request.info('******************2')
            userIP = datacheck.getIP(request)
            logger_request.info('******************3')
            logger_request.info(userIP)
            logger_request.info(user.username)
            logger_request.info(option)
            logger_request.info('******************35')
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
            logger_request.info('******************4')
        elif requestParam['option'] == '2':
            need.isActive = False
            need.save()
            option = '删除了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        elif requestParam['option'] == '3' and need.isActive == False:
            need.isActive = True
            need.save()
            option = '恢复了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        else:
            data = {
                'code': 0,
                'msg': 'option error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    elif userType == '3':
        if requestParam['option'] == '0':
            need.isActive = False
            need.save()
            option = '删除了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        elif requestParam['option'] == '1' and need.isActive == False:
            need.isActive = True
            need.save()
            option = '恢复了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        else:
            data = {
                'code': 0,
                'msg': 'option error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    elif userType == '1':
        if requestParam['option'] == '0':
            handle = NeedHandle.objects.create(
                user=user,
                need=need,
                handleContent=requestParam['result'],
            )
            need.needState = 1
            need.ishandle = True
            need.save()
            announcementCreate(
                type='need',
                num='2',
                userType='3',
                userId=user.id,
                softwareVersionId=need.softwareVersion.id,
                IdNum=need.id
            )
            option = '回复了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        elif requestParam['option'] == '1':
            reject = NeedHandle.objects.create(
                user=user,
                need=need,
                rejectResult=requestParam['result'],
            )
            need.ishandle = True
            need.needState = 2
            need.examineState = 2
            need.save()
            announcementCreate(
                type='need',
                num='3',
                userType='3',
                userId=user.id,
                softwareVersionId=need.softwareVersion.id,
                IdNum=need.id
            )
            option = '驳回了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        elif requestParam['option'] == '2':
            need.isActive = False
            need.save()
            option = '删除了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        elif requestParam['option'] == '3' and need.isActive == False:
            need.isActive = True
            need.save()
            option = '恢复了' + str(need.title) + '需求'
            userIP = datacheck.getIP(request)
            log = UserLog.objects.create(
                user=user,
                userIP=userIP,
                operate=option,
            )
        else:
            data = {
                'code': 0,
                'msg': 'option error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        data = {
            'code': 0,
            'msg': 'type error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)
